package com.learn.dict.handler;

import cn.hutool.core.map.MapUtil;
import com.google.common.collect.Maps;
import com.learn.dict.handler.business.IBusinessDictHandler;
import com.learn.dict.handler.dictdata.AbstractDictDataHandler;
import com.learn.dict.handler.dictdata.DefaultDictDataHandler;
import com.learn.dict.handler.dictdata.IDictDataHandler;
import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

/**
 * 功能描述: 通过spring，将业务字典实现类注册到map中，方便使用 <br/>
 *
 * @author: MI
 * @email: 448341911@qq.com
 * @createDate: 2023/10/22 22:31
 * @updateUser: MI
 * @updateDate: 2023/10/22 22:31
 * @updateRemark: 修改内容
 * @version: v1.0
 */
@Getter
@Component
public class DictHandlerAware implements ApplicationContextAware {

    private final Map<String, IBusinessDictHandler> handlerMap = Maps.newHashMap();

    /**
     * 设置默认实现
     */
    private IDictDataHandler dictHandler = new DefaultDictDataHandler();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 根据接口类型返回相应的所有bean
        Map<String, IBusinessDictHandler> map = applicationContext.getBeansOfType(IBusinessDictHandler.class);
        Set<Map.Entry<String, IBusinessDictHandler>> entries = map.entrySet();
        for (Map.Entry<String, IBusinessDictHandler> entry : entries) {
            this.handlerMap.put(entry.getValue().typeCode(), entry.getValue());
        }
        // 根据抽象类，返回字典类型
        Map<String, AbstractDictDataHandler> dataHandlerMap = applicationContext.getBeansOfType(AbstractDictDataHandler.class);
        if (MapUtil.isNotEmpty(dataHandlerMap)) {
            dictHandler = dataHandlerMap.entrySet().iterator().next().getValue();
        }
    }
}
